package com.example.logisticsingle.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * Cookie工具类

 *
 */
public class CookieUtil {
    // 默认缓存时间,单位/秒
    public static int COOKIE_MAX_AGE = Integer.MAX_VALUE;

    // 保存路径,根路径
    public static String COOKIE_PATH = "/iam";
    /**
     * 保存Cookie信息
     * @param response
     * @param key
     * @param value
     * @param ifRemember
     */
    public static void set(HttpServletResponse response, String key, String value, boolean isRemember) {
        int age = isRemember?COOKIE_MAX_AGE:-1;
        set(response, key, value, null, COOKIE_PATH, age, true);
    }

    public static void set(HttpServletResponse response, String key, String value, int age,boolean isRemember) {
        set(response, key, value, null, COOKIE_PATH, age, true);
    }
    /**
     * 从Cookie中移除信息
     * @param request
     * @param response
     * @param key
     */
    public static void remove(HttpServletRequest request, HttpServletResponse response, String key) {
        Cookie cookie = get(request, key);
        if (cookie != null) {
            set(response, key, "", null, COOKIE_PATH, 0, true);
        }
    }
    /**
     * 保存Cookie
     * @param response
     * @param key
     * @param value
     * @param domain
     * @param path
     * @param maxAge
     * @param isHttpOnly
     */
    private static void set(HttpServletResponse response, String key, String value, String domain, String path, int maxAge, boolean isHttpOnly) {
        Cookie cookie = new Cookie(key, value);
        if (domain != null) {
            cookie.setDomain(domain);
        }
        cookie.setPath(path);
        cookie.setMaxAge(maxAge);
        cookie.setHttpOnly(isHttpOnly);
        response.addCookie(cookie);
    }
    /**
     * 获取Cooike信息
     * @param request
     * @param key
     * @return
     */
    public static Cookie get(HttpServletRequest request, String key) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(key)) {
                    return cookie;
                }
            }
        }
        return null;
    }
    /**
     * 查询value
     *
     * @param request
     * @param key
     * @return
     */
    public static String getValue(HttpServletRequest request, String key) {
        Cookie cookie = get(request, key);
        if (cookie != null) {
            return cookie.getValue();
        }
        return null;
    }
}
